
import logging
from django.db.models import Q
from django.utils import timezone
from django.shortcuts import get_object_or_404

from rest_framework import status, viewsets, mixins, filters
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from django_filters.rest_framework import DjangoFilterBackend

from .models import LocationRecord, Milestone, TrackingSettings
from .serializers import (
    LocationRecordSerializer, LocationRecordCreateSerializer,
    MilestoneSerializer, MilestoneCreateSerializer,
    TrackingSettingsSerializer, TrackingSettingsUpdateSerializer
)
from order_app.models import Order
from vehicle_app.models import Vehicle

logger = logging.getLogger(__name__)


class LocationRecordViewSet(viewsets.ModelViewSet):
    """位置记录视图集"""
    
    queryset = LocationRecord.objects.all()
    serializer_class = LocationRecordSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ['vehicle', 'order']
    ordering_fields = ['created_at']
    ordering = ['-created_at']
    
    def get_serializer_class(self):
        """根据操作选择序列化器"""
        if self.action == 'create' or self.action == 'batch_create':
            return LocationRecordCreateSerializer
        return self.serializer_class
    
    def get_queryset(self):
        """获取查询集"""
        queryset = super().get_queryset()
        
        # 如果是获取订单轨迹，则根据订单ID筛选
        order_id = self.request.query_params.get('order_id')
        if order_id:
            queryset = queryset.filter(order_id=order_id)
        
        # 如果是获取车辆轨迹，则根据车辆ID筛选
        vehicle_id = self.request.query_params.get('vehicle_id')
        if vehicle_id:
            queryset = queryset.filter(vehicle_id=vehicle_id)
        
        # 如果指定了时间范围，则根据时间范围筛选
        start_time = self.request.query_params.get('start_time')
        end_time = self.request.query_params.get('end_time')
        if start_time:
            queryset = queryset.filter(created_at__gte=start_time)
        if end_time:
            queryset = queryset.filter(created_at__lte=end_time)
        
        return queryset
    
    def create(self, request, *args, **kwargs):
        """创建位置记录"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 获取订单
        order_id = serializer.validated_data.get('order')
        if order_id:
            order = get_object_or_404(Order, id=order_id.id)
            
            # 检查当前用户是否是订单的车主
            if request.user != order.driver:
                return Response(
                    {'error': '只有订单的车主才能上传位置'},
                    status=status.HTTP_403_FORBIDDEN
                )
            
            # 获取车辆
            vehicle = order.vehicle
        else:
            # 如果没有指定订单，则根据用户获取车辆
            try:
                vehicle = Vehicle.objects.filter(user=request.user).first()
                if not vehicle:
                    return Response(
                        {'error': '未找到您的车辆信息'},
                        status=status.HTTP_404_NOT_FOUND
                    )
            except Vehicle.DoesNotExist:
                return Response(
                    {'error': '未找到您的车辆信息'},
                    status=status.HTTP_404_NOT_FOUND
                )
        
        # 创建位置记录
        location_record = LocationRecord.objects.create(
            vehicle=vehicle,
            order=order_id,
            longitude=serializer.validated_data.get('longitude'),
            latitude=serializer.validated_data.get('latitude'),
            altitude=serializer.validated_data.get('altitude'),
            accuracy=serializer.validated_data.get('accuracy'),
            speed=serializer.validated_data.get('speed'),
            direction=serializer.validated_data.get('direction'),
            address=serializer.validated_data.get('address'),
            province=serializer.validated_data.get('province'),
            city=serializer.validated_data.get('city'),
            district=serializer.validated_data.get('district')
        )
        
        # 更新车辆位置
        vehicle.current_location = serializer.validated_data.get('address') or vehicle.current_location
        vehicle.longitude = serializer.validated_data.get('longitude')
        vehicle.latitude = serializer.validated_data.get('latitude')
        vehicle.location_updated_at = timezone.now()
        vehicle.save()
        
        # 通过WebSocket推送位置更新
        from channels.layers import get_channel_layer
        from asgiref.sync import async_to_sync
        
        channel_layer = get_channel_layer()
        
        # 推送给订单相关用户
        if location_record.order:
            order_group_name = f"order_{location_record.order.id}"
            async_to_sync(channel_layer.group_send)(
                order_group_name,
                {
                    "type": "location_update",
                    "message": {
                        "location_record_id": location_record.id,
                        "latitude": location_record.latitude,
                        "longitude": location_record.longitude,
                        "timestamp": timezone.now().isoformat(),
                        "vehicle_id": location_record.vehicle.id if location_record.vehicle else None,
                        "order_id": location_record.order.id if location_record.order else None
                    }
                }
            )
        
        # 推送给车辆相关用户
        if location_record.vehicle:
            vehicle_group_name = f"vehicle_{location_record.vehicle.id}"
            async_to_sync(channel_layer.group_send)(
                vehicle_group_name,
                {
                    "type": "location_update",
                    "message": {
                        "location_record_id": location_record.id,
                        "latitude": location_record.latitude,
                        "longitude": location_record.longitude,
                        "timestamp": timezone.now().isoformat(),
                        "vehicle_id": location_record.vehicle.id if location_record.vehicle else None,
                        "order_id": location_record.order.id if location_record.order else None
                    }
                }
            )
        
        return Response(
            LocationRecordSerializer(location_record).data,
            status=status.HTTP_201_CREATED
        )
    
    @action(detail=False, methods=['post'])
    def batch_create(self, request):
        """批量创建位置记录"""
        records = request.data
        if not isinstance(records, list):
            return Response(
                {'error': '请提供位置记录列表'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        created_records = []
        for record_data in records:
            serializer = self.get_serializer(data=record_data)
            if serializer.is_valid():
                # 获取订单
                order_id = serializer.validated_data.get('order')
                if order_id:
                    try:
                        order = Order.objects.get(id=order_id.id)
                        
                        # 检查当前用户是否是订单的车主
                        if request.user != order.driver:
                            continue
                        
                        # 获取车辆
                        vehicle = order.vehicle
                    except Order.DoesNotExist:
                        continue
                else:
                    # 如果没有指定订单，则根据用户获取车辆
                    try:
                        vehicle = Vehicle.objects.filter(user=request.user).first()
                        if not vehicle:
                            continue
                    except Vehicle.DoesNotExist:
                        continue
                
                # 创建位置记录
                location_record = LocationRecord.objects.create(
                    vehicle=vehicle,
                    order=order_id,
                    longitude=serializer.validated_data.get('longitude'),
                    latitude=serializer.validated_data.get('latitude'),
                    altitude=serializer.validated_data.get('altitude'),
                    accuracy=serializer.validated_data.get('accuracy'),
                    speed=serializer.validated_data.get('speed'),
                    direction=serializer.validated_data.get('direction'),
                    address=serializer.validated_data.get('address'),
                    province=serializer.validated_data.get('province'),
                    city=serializer.validated_data.get('city'),
                    district=serializer.validated_data.get('district')
                )
                
                created_records.append(location_record)
        
        if created_records:
            # 更新车辆位置（使用最新的记录）
            latest_record = created_records[-1]
            vehicle = latest_record.vehicle
            vehicle.current_location = latest_record.address or vehicle.current_location
            vehicle.longitude = latest_record.longitude
            vehicle.latitude = latest_record.latitude
            vehicle.location_updated_at = timezone.now()
            vehicle.save()
            
            # TODO: 通过WebSocket推送位置更新
        
        return Response(
            {'message': f'成功创建{len(created_records)}条位置记录'},
            status=status.HTTP_201_CREATED
        )
    
    @action(detail=False, methods=['get'])
    def latest(self, request):
        """获取最新位置记录"""
        vehicle_id = request.query_params.get('vehicle_id')
        order_id = request.query_params.get('order_id')
        
        if not vehicle_id and not order_id:
            return Response(
                {'error': '请提供车辆ID或订单ID'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        try:
            if order_id:
                # 获取订单的最新位置记录
                location_record = LocationRecord.objects.filter(order_id=order_id).latest('created_at')
            else:
                # 获取车辆的最新位置记录
                location_record = LocationRecord.objects.filter(vehicle_id=vehicle_id).latest('created_at')
            
            return Response(LocationRecordSerializer(location_record).data)
        except LocationRecord.DoesNotExist:
            return Response(
                {'error': '未找到位置记录'},
                status=status.HTTP_404_NOT_FOUND
            )


class MilestoneViewSet(viewsets.ModelViewSet):
    """里程碑视图集"""
    
    queryset = Milestone.objects.all()
    serializer_class = MilestoneSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ['order', 'milestone_type']
    ordering_fields = ['created_at']
    ordering = ['order', 'created_at']
    
    def get_serializer_class(self):
        """根据操作选择序列化器"""
        if self.action == 'create':
            return MilestoneCreateSerializer
        return self.serializer_class
    
    def create(self, request, *args, **kwargs):
        """创建里程碑"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 获取订单
        order_id = serializer.validated_data.get('order').id
        order = get_object_or_404(Order, id=order_id)
        
        # 检查当前用户是否是订单的货主或车主
        if request.user != order.shipper and request.user != order.driver:
            return Response(
                {'error': '只有订单的货主或车主才能创建里程碑'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 创建里程碑
        milestone = Milestone.objects.create(
            order=order,
            milestone_type=serializer.validated_data.get('milestone_type'),
            description=serializer.validated_data.get('description', ''),
            longitude=serializer.validated_data.get('longitude'),
            latitude=serializer.validated_data.get('latitude'),
            address=serializer.validated_data.get('address')
        )
        
        # 根据里程碑类型更新订单状态
        milestone_type = serializer.validated_data.get('milestone_type')
        if milestone_type == Milestone.Type.START:
            if order.status == Order.Status.PENDING_LOADING:
                order.status = Order.Status.IN_TRANSIT
                order.actual_loading_time = timezone.now()
                order.save()
        elif milestone_type == Milestone.Type.ARRIVE_DELIVERY:
            if order.status == Order.Status.IN_TRANSIT:
                order.status = Order.Status.DELIVERED
                order.actual_delivery_time = timezone.now()
                order.save()
        elif milestone_type == Milestone.Type.COMPLETE:
            if order.status == Order.Status.DELIVERED:
                order.status = Order.Status.COMPLETED
                order.save()
        
        # TODO: 发送通知给相关用户
        
        return Response(
            MilestoneSerializer(milestone).data,
            status=status.HTTP_201_CREATED
        )


class TrackingSettingsViewSet(viewsets.GenericViewSet,
                             mixins.RetrieveModelMixin,
                             mixins.UpdateModelMixin,
                             mixins.ListModelMixin):
    """跟踪设置视图集"""
    
    queryset = TrackingSettings.objects.all()
    serializer_class = TrackingSettingsSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['vehicle']
    
    def get_serializer_class(self):
        """根据操作选择序列化器"""
        if self.action == 'update' or self.action == 'partial_update':
            return TrackingSettingsUpdateSerializer
        return self.serializer_class
    
    def get_queryset(self):
        """获取查询集"""
        queryset = super().get_queryset()
        
        # 只返回当前用户的车辆的跟踪设置
        return queryset.filter(vehicle__user=self.request.user)
    
    @action(detail=False, methods=['get'])
    def my_settings(self, request):
        """获取我的跟踪设置"""
        vehicle_id = request.query_params.get('vehicle_id')
        
        if not vehicle_id:
            return Response(
                {'error': '请提供车辆ID'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        try:
            # 检查车辆是否属于当前用户
            vehicle = Vehicle.objects.get(id=vehicle_id, user=request.user)
            
            # 获取或创建跟踪设置
            settings, created = TrackingSettings.objects.get_or_create(
                vehicle=vehicle,
                defaults={
                    'report_interval': 60,
                    'report_distance': 100,
                    'power_saving_mode': False,
                    'power_saving_interval': 300,
                    'is_tracking_enabled': True
                }
            )
            
            return Response(TrackingSettingsSerializer(settings).data)
        except Vehicle.DoesNotExist:
            return Response(
                {'error': '未找到您的车辆信息'},
                status=status.HTTP_404_NOT_FOUND
            )